package pers.vic.base.handle.convert;

import java.io.IOException;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import pers.vic.base.annoation.AppendJsonField;

/**
 * 追加JSON字段的序列化方法
 * @See @AppendJsonField
// *  use for field like:   @AppendJsonField(key="idDesc", keyValyeDesc= {"1:ZHANGSAN", "2:LISI"})
 * @author VIC
 *
 */
public class AppendJsonFieldSerialize extends JsonSerializer<Integer> implements ContextualSerializer {

	private String key;

	private String[] keyValyeDesc;
	
	public AppendJsonFieldSerialize() {
		super();
	}

	public AppendJsonFieldSerialize(String key, String[] keyValyeDesc) {
		super();
		this.key = key;
		this.keyValyeDesc = keyValyeDesc;
	}

	@Override
	public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty)
			throws JsonMappingException {
		if (beanProperty != null) { // 为空直接跳过
			Class<?> clzType = beanProperty.getType().getRawClass();
			if (Objects.equals(clzType, int.class) || Objects.equals(clzType, Integer.class)) { // 非 Integer 类直接跳过
				AppendJsonField appendJsonField = beanProperty.getAnnotation(AppendJsonField.class);
				if (appendJsonField == null) {
					appendJsonField = beanProperty.getContextAnnotation(AppendJsonField.class);
				}
				if (appendJsonField != null) { // 如果能得到注解，
					String key = appendJsonField.key();
					String[] keyValyeDesc = appendJsonField.keyValyeDesc();
					return new AppendJsonFieldSerialize(key, keyValyeDesc);
				}
			}
			return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
		}
		return serializerProvider.findNullValueSerializer(beanProperty);
	}

	@Override
	public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
		gen.writeNumber(value);
		if(StringUtils.isNoneEmpty(key) && keyValyeDesc != null) {
			for(String kv : keyValyeDesc) {
				if(kv.split(":").length == 2  && String.valueOf(value).equals(kv.split(":")[0])) {
					gen.writeStringField(key, kv.split(":")[1]);
					break;
				}
			}
		}
	}
	
}
